/**
 * 15-600: Java and J2EE
 * Instructor: Jeff Eppinger
 * Done By:	Mohammad al Khani
 * Date Dec 10, 2011
 */

package controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import model.Model;
import model.UserDAO;

import org.mybeans.form.FormBeanFactory;

import dataBeans.User;
import exceptions.MyWebsiteException;

import formBean.LoginForm;
import formBean.RegistrationForm;

public class RegisterAction extends Action {

	private FormBeanFactory<RegistrationForm> formBeanFactory = FormBeanFactory.getInstance(RegistrationForm.class);
	private UserDAO userDAO;
	
	public RegisterAction(Model model){
		
	}
	
	@Override
	public String getName() {
		// TODO Auto-generated method stub
		return "register.do";
	}

	@Override
	public String perform(HttpServletRequest request) {
		  List<String> errors = new ArrayList<String>();
	        request.setAttribute("errors",errors);
	        
	        try {
		    	RegistrationForm form = formBeanFactory.create(request);
		        request.setAttribute("form",form);
		        if (!form.isPresent()) {
		            return "register.jsp";
		        }

		        // Any validation errors?
		        errors.addAll(form.getValidationErrors());
		        if (errors.size() != 0) {
		            return "register.jsp";
		        }
		        userDAO = new UserDAO();
		        userDAO.create(form.getFirstName(), form.getLastName(), form.getEmail(), form.getPassword());
		        User user = userDAO.login(form.getEmail(), form.getPassword());
		        
		        request.getSession().setAttribute("user", user);
		        String webapp = request.getContextPath();
				return webapp + "/manage.do";
		        //return "manage.do";
	        }
	        catch(MyWebsiteException e){
	        	errors.add("User already exists");
	        	return "register.jsp";
	        }
	        catch(Exception e){
	        	e.printStackTrace();
	        	return "error.jsp";
	        }
	}

}
